package com.sxygsj.android.personnelscreen.plugin_jiguang.userInfoList

import android.app.Activity
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import android.os.Bundle
import android.os.CountDownTimer
import android.view.View
import androidx.fragment.app.Fragment
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.shencoder.pagergridlayoutmanager.PagerGridLayoutManager
import com.sxygsj.android.personnelscreen.plugin_jiguang.main.MainActivity
import com.sxygsj.android.personnelscreen.plugin_jiguang.R
import com.sxygsj.android.personnelscreen.plugin_jiguang.htppCallBack.HttpCallBackEntity
import com.tencent.mmkv.MMKV
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList

class UserInfoListFragment : Fragment() {

    private var recyclerView: RecyclerView? = null

    private val layoutManager: PagerGridLayoutManager by lazy {
        PagerGridLayoutManager(
            4,
            4,
            PagerGridLayoutManager.VERTICAL
        )
    }
    private val adapter: UserInfoListAdapter by lazy { UserInfoListAdapter() }

    private lateinit var activity: MainActivity
  companion object{
      var cardReaderNumber="0005793C"
      var distance=2
      var pageIntervalTime=5L
  }

      var requestTime=0L
    override fun onAttach(activity: Activity) {
        super.onAttach(activity)
        this.activity = activity as MainActivity
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val mmkv=MMKV.mmkvWithID("configureInfo")!!
        cardReaderNumber=mmkv.decodeString("cardReaderNumber", "0005793C")!!
        distance=mmkv.decodeInt("distance", 9)
        pageIntervalTime=mmkv.decodeLong("pageIntervalTime", 5)
        return inflater.inflate(R.layout.fragment_user_info_list, container, false)
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        recyclerView = view.findViewById(R.id.userInfoList_recycler)
        recyclerView!!.layoutManager = layoutManager
        recyclerView!!.adapter = adapter
        requestUserInfo(MainActivity.masterServerIP)
        requestUserInfo(MainActivity.standbyServerIP)




//        val newScheduledThreadPool = Executors.newScheduledThreadPool(3)
//        newScheduledThreadPool.scheduleAtFixedRate(Runnable {
//          Log.e("TAG","=masterServerIP="+MainActivity.masterServerIP)
//          Log.e("TAG","=standbyServerIP="+MainActivity.standbyServerIP)
//          Log.e("TAG","=advertisingScreenTitle="+MainActivity.advertisingScreenTitle)
//          Log.e("TAG","=scrollPlaybackSpeed="+MainActivity.scrollPlaybackSpeed)
//          Log.e("TAG","=mAdvertisingSwitchingTime="+MainActivity.mAdvertisingSwitchingTime)
//
//          Log.e("TAG","=cardReaderNumber="+ cardReaderNumber)
//          Log.e("TAG","=distance="+ distance)
//          Log.e("TAG","=pageIntervalTime="+ pageIntervalTime)
//
//        },1000,1000,TimeUnit.MILLISECONDS)
    }



    fun requestUserInfo(ip: String) {

        val weakHashMap = WeakHashMap<String, String>()
        weakHashMap["CardReaderID"] = cardReaderNumber
        weakHashMap["Distance"] = distance.toString()
        OkGo.post<String>("http://${ip}/listCheckCard")
            .upJson(Gson().toJson(weakHashMap))
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String>?) {
                    val json = response!!.body()
                    val httpCallBack = Gson().fromJson<HttpCallBackEntity<List<UserInfo>>>(
                        json,
                        object : TypeToken<HttpCallBackEntity<List<UserInfo?>?>>() {}.type
                    )
                    if (httpCallBack.code == 0 && httpCallBack.msg.equals("查询成功")) {
                        val copyOnWriteArrayList = CopyOnWriteArrayList<UserInfo>()
                        copyOnWriteArrayList.addAll(httpCallBack.data)
                        if (copyOnWriteArrayList.size > 0) {
                            requestTime=System.currentTimeMillis()
                         //   activity.showUserInfoListFragment()
                        }

                        adapter.submitList(copyOnWriteArrayList)

                        val size = adapter.currentList.size
                        if (size > 16) {
                            var page = size / 16
                            val i = size % 16
                            if (i > 0) {
                                page = page + 1
                            }
                                object : CountDownTimer(
                                pageIntervalTime * 1000,
                                page.toLong() * pageIntervalTime * 1000
                            ) {
                                override fun onTick(p0: Long) {
                                    layoutManager.scrollToNextPager()
                                }

                                override fun onFinish() {
                                    requestUserInfo(ip)
                                }
                            }.start()
                        } else {
                            requestUserInfo(ip)
                        }
                    } else {
                        requestUserInfo(ip)
                    }
                }

                override fun onError(response: Response<String>?) {
                    super.onError(response)
                    requestUserInfo(ip)
                }

            })
    }

}